<template>
  <component
    :is="`el-${column.search.el}`"
    v-if="column.search && column.search.el"
    v-model="searchParam[column.search.key || handleProp(column.prop)]"
    range-separator="至"
    start-placeholder="开始时间"
    end-placeholder="结束时间"
    :data="column.search.el === 'tree-select' ? columnEnum : []"
    :options="['cascader', 'select-v2'].includes(column.search.el) ? columnEnum : []"
    :clearable="clearable"
    v-bind="handleSearchProps"
  >
    <template v-if="column.search.el === 'cascader'" v-slot="data">
      <span>{{ data[fieldNames.label] }}</span>
    </template>
    <template v-if="column.search.el === 'select'">
      <component
        :is="`el-option`"
        v-for="(col, index) in columnEnum"
        :key="index"
        :label="col[fieldNames.label]"
        :value="col[fieldNames.value]"
      />
    </template>
    <slot v-else />
  </component>
</template>

<script>
export default {
  props: {
    column: Object,
    searchParam: Object
  },
  computed: {
    fieldNames() {
      return {
        label: this.column.fieldNames && this.column.fieldNames.label ? this.column.fieldNames.label : 'label',
        value: this.column.fieldNames && this.column.fieldNames.value ? this.column.fieldNames.value : 'value'
      }
    },
    columnEnum() {
      return this.column.enum || []
    },
    handleSearchProps() {
      const label = this.fieldNames.label
      const value = this.fieldNames.value
      const searchEl = this.column.search && this.column.search.el
      const searchProps = this.column.search && this.column.search.props ? this.column.search.props : {}
      let handleProps = searchProps
      if (searchEl === 'tree-select') {
        handleProps = {
          ...searchProps,
          props: { label, ...searchProps.props },
          nodeKey: value
        }
      }
      if (searchEl === 'cascader') {
        handleProps = {
          ...searchProps,
          props: { label, value, ...searchProps.props }
        }
      }
      return handleProps
    },
    placeholder() {
      const search = this.column.search
      return search && search.props && search.props.placeholder
        ? search.props.placeholder
        : search && search.el === 'input'
          ? '请输入'
          : '请选择'
    },
    clearable() {
      const search = this.column.search
      return (
        search && search.props && search.props.clearable
          ? search.props.clearable
          : search && (search.defaultValue == null || search.defaultValue === undefined)
      )
    }
  },
  methods: {
    handleProp(prop) {
      const propArr = prop.split('.')
      if (propArr.length === 1) return prop
      return propArr[propArr.length - 1]
    }
  }
}
</script>
